package com.canbot.u05.activity.attendance;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.button.MaterialButton;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.canbot.u05.MainApplication;
import com.canbot.u05.R;
import com.canbot.u05.activity.BaseActivityNoTitle;
import com.canbot.u05.activity.ChoosePicActivity;
import com.canbot.u05.bean.AttendanceSettings;
import com.canbot.u05.glide.GlideApp;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.socket.MsgSendUtils;
import com.canbot.u05.socket.MsgType;
import com.canbot.u05.utils.Config;
import com.canbot.u05.utils.ConstUtils;
import com.canbot.u05.utils.Logger;
import com.canbot.u05.utils.OkHttpUtils;
import com.canbot.u05.utils.PathConst;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.view.GlideCircleTransform;
import com.canbot.u05.widget.LoadingDialogUtils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 考勤管理员设置
 */
public class AttendanceAdminActivity extends BaseActivityNoTitle implements View.OnClickListener {

        private String[] fileName = new String[]{"glysz_kq_u05_001.mp3", "glysz_kq_u05_002.mp3"};

        private String[] updateName = new String[]{"tbcg_kq_u05_001.wav", "tbcg_kq_u05_002.wav"};

        public static final SimpleDateFormat formatDate = new SimpleDateFormat("yyyy/MM/dd", Locale.CHINA);

        private Button btnBack;

        private MaterialButton btnSure;

        private ImageView imageView;

        private EditText editText;

        private static final int FACE_IMAGE = 1;

        private static final String TAG = "AttendanceAdminActivity";
        private static final int FINISH = 10;


        private Dialog dialogLoading;

        private String identification;

        private String path;

        private AttendanceSettings attendanceSettings;

        private String email;


        private Handler mHandler = new Handler(){
                @Override
                public void handleMessage(Message msg) {
                        switch (msg.what){
                                case FINISH:
                                        MainApplication.finishActivity(AttendanceGroupActivity.class.getName());
                                        MainApplication.finishActivity(AttendanceSettingTimeActivity.class.getName());
                                        finish();
                                        overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit);
                                        break;
                        }
                }
        };

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_kq_admin);
                attendanceSettings = (AttendanceSettings)getIntent().getSerializableExtra("settings");
                if (attendanceSettings != null){
                        if (attendanceSettings.getAdminId() != null){
                                identification = attendanceSettings.getAdminId() ;
                        }
                }
                int index = (int) (Math.random() * fileName.length);
                MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.AUDIO_ATTENDANCE_DIR + fileName[index]);
                setViews();
        }


        /**
         * 用户考勤信息显示界面
         */
        private void setViews() {

                editText = findViewById(R.id.edit_email);
                btnBack = findViewById(R.id.imageView_back);
                btnSure = findViewById(R.id.btn_sure);
                TextView text_tip = findViewById(R.id.text_tip);
                String string =  getResources().getString(R.string.attendance_info_tip);
                String sFinal1 = String.format(string, Config.ROBOT_NAME);
                text_tip.setText(sFinal1);
                imageView = findViewById(R.id.image);

                btnBack.setOnClickListener(this);
                btnSure.setOnClickListener(this);
                imageView.setOnClickListener(this);


                if (!TextUtils.isEmpty(attendanceSettings.getAdminEmail())){
                        editText.setText(attendanceSettings.getAdminEmail());
                }

                if (!TextUtils.isEmpty(attendanceSettings.getAdminPicPath())){
                        path =  attendanceSettings.getAdminPicPath();
                        showView();
                }
        }

        private void showView(){
                Logger.e(TAG,"path = "+IpMsgConst.HTTP_URL_CHEST +PathConst.FACES_THUMB_DIR+ path);
                GlideApp.with(this).clear(imageView);
                // 加载图片
                GlideApp.with(this)
                        .load(IpMsgConst.HTTP_URL_CHEST +PathConst.FACES_ABS_DIR+ path)
                        .thumbnail(Glide.with(this).load(IpMsgConst.HTTP_URL_CHEST + PathConst.FACES_THUMB_DIR+path).transform(new GlideCircleTransform(this)))
                        .placeholder(R.drawable.profile_pre)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .transform(new GlideCircleTransform(this))
                        .into(imageView);

        }

        /**
         * 提交管理员信息
         */
        private void commitData() {

                if (TextUtils.isEmpty(identification) && TextUtils.isEmpty(email)) {
                        ToastTools.newInstance(this).showText(getString(R.string.attendance_admin_email_empty_tip2));
                        return;

                }
                //如果管理员为空 则提示不能提交
                if (TextUtils.isEmpty(identification) || TextUtils.isEmpty(path)) {
                        ToastTools.newInstance(this).showText(getString(R.string.attendance_admin_empty_tip));
                        return;
                }
                if (TextUtils.isEmpty(email)) {
                        ToastTools.newInstance(this).showText(getString(R.string.attendance_admin_email_empty_tip));
                        return;
                }
                //邮箱格式验证
                if (!isValidEmail(email)) {
                        ToastTools.newInstance(this).showText(getString(R.string.attendance_admin_email_pattern));
                        return;
                }


                attendanceSettings.setAdminEmail(email);
                attendanceSettings.setAdminId(identification);
                attendanceSettings.setAdminPicPath(path);
                dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getString(R.string.attendance_commit_tip));
                Logger.e(TAG, "commitData:" +email +"  id=" + identification +" path="+path);
                HashMap<String, Object> hasMap = new HashMap<>();
                hasMap.put("attendanceSettings", JSON.toJSONString(attendanceSettings));
                String editDate = formatDate.format(Calendar.getInstance().getTime());
                hasMap.put("user_edit_date",editDate );


                OkHttpUtils.upLoadFile("http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755/" + ConstUtils.URL_ATTENDANCE_SET, hasMap, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(String result) {

                                Logger.e("save", "onSuccess:" + result);
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                int index = (int) (Math.random() * updateName.length);
                                                MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND,PathConst.AUDIO_ATTENDANCE_DIR +updateName[index]);
                                                ToastTools.newInstance(AttendanceAdminActivity.this).showText(getString(R.string.attendance_setting_success));
                                                LoadingDialogUtils.closeDialog(dialogLoading);
                                                mHandler.sendEmptyMessageDelayed(FINISH,500);
                                        }
                                });
                        }

                        @Override
                        public void onFailure() {
                                Logger.e("save", "onFailure");
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                ToastTools.newInstance(AttendanceAdminActivity.this).showText(AttendanceAdminActivity.this.getString(R.string.network_error));
                                                LoadingDialogUtils.closeDialog(dialogLoading);
                                        }
                                });
                        }
                });
        }

        @Override
        public void onClick(View view) {

                switch (view.getId()) {
                        case R.id.imageView_back:
                                finish();
                                break;

                        case R.id.btn_sure:
                                email = editText.getText().toString();
                                commitData();
                                break;

                        case R.id.image:
                                //跳转至选择图片界面  /temp/faces/
                                Intent intent = new Intent(this, AttendanceChooseFaceActivity.class);
                                intent.putExtra("identification", attendanceSettings.getAdminId());
                                startActivityForResult(intent, FACE_IMAGE);
                                break;
                }
        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);
                if (resultCode == RESULT_OK && data != null) {
                        if (requestCode == FACE_IMAGE) {
                                identification = data.getStringExtra("identification");
                                path = data.getStringExtra("path");
                                if (path != null) {
                                        Logger.e(TAG, "返回来的数据是 pic " + path);
                                        showView();
                                }
                        }
                }
        }


        /**
         * 验证是否为正确的邮箱号
         *
         * @param email
         * @return
         */
        public static boolean isValidEmail(String email) {
//                String reg = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
                String reg = "[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?";
                Pattern pattern = Pattern.compile(reg);
                boolean flag = false;
                if (email != null) {
                        Matcher matcher = pattern.matcher(email);
                        flag = matcher.matches();
                }
                return flag;
        }


        @Override
        protected void onPause() {
                if (dialogLoading != null && dialogLoading.isShowing()) {
                        LoadingDialogUtils.closeDialog(dialogLoading);
                }
                super.onPause();
        }
}
